import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * 
 * @author Isaac
 *
 *	This class is the main class of the server
 */
public class Mymain
{
	private static int Xsize;
	private static int Ysize;
	private static Frame frame=null;
	private static Boom bmain;
	private static Vector agentsVect;
	
	/**
	 * This procedure parses the message which was accepted from the client
	 * 
	 * @param in - a message to be parsed by the server
	 * @return - a message to be sent as a feedback to the client.
	 */
	public static String parseInput(String in){
		String inn;
		String feedBack; 
                inn =in.trim();
                feedBack="";
	     StringTokenizer st = new StringTokenizer(inn);
	     if (st.hasMoreTokens()) {
	         String command = st.nextToken();
	         if (command.compareTo("Board")==0){ //parse board
	         	Xsize = Integer.parseInt(st.nextToken());
	         	Ysize = Integer.parseInt(st.nextToken());
                        if(frame!=null)
                            frame.dispose();
	         	frame = new Frame("Board");
	    		//create a frame for the crawler window applet
 	    		bmain = new Boom();
	    		frame.add(bmain,BorderLayout.CENTER);
	    		frame.setSize(Xsize*20,Ysize*20);
	    		frame.setLocation(20,20);
                        frame.setAlwaysOnTop(true);
	    		bmain.init(Xsize,Ysize);
	    		bmain.start();
	    		frame.setVisible(true);
	    		//frame.setAlwaysOnTop(true);
	    		
	    		frame.addWindowListener(new WindowAdapter()
	    				{
	    			public void windowClosing(WindowEvent e)
	    			{
	    				  frame.dispose();
                                          frame=null;
	    			}
	    				});
                         
                        agentsVect=new Vector();
	    		feedBack="Board Done!";
	         }
	         else if(command.compareTo("Walls")==0){
	         	while(st.hasMoreTokens()){
	         		int cell = Integer.parseInt(st.nextToken());
	         		bmain.setWall(cell-1);
	         	}
			frame.pack();
	         	feedBack="Walls Done!";
	         }
	         else if(command.compareTo("Flags")==0){
	         	while(st.hasMoreTokens()){
	         		int cell = Integer.parseInt(st.nextToken());
	         		bmain.setFlag(cell-1);
	         	}
	         	feedBack="Flags Done!";
	         }
	         else if(command.compareTo("Agent")==0){
	         	
	         	String name = st.nextToken();
	         	String color = st.nextToken();
	         	String  orientation= st.nextToken();
	         	int cell = ((Integer.parseInt(st.nextToken()))-1);
	         	
	         	SingleAgent agent1 = new SingleAgent(name,color,orientation,cell,Xsize,Ysize);
	         	bmain.setAgent(agent1);
	         	agentsVect.addElement(agent1);
	         	feedBack="Agent Done!";
	         }
	         else if(command.compareTo("MoveAgent")==0){
	         	String agentName = st.nextToken();
	         	boolean found = false;
	         	int i=0;
	         	for (i=0;i<agentsVect.size() && !found;i++){
	         		SingleAgent tmp = ((SingleAgent)agentsVect.elementAt(i));
	         		if(agentName.compareToIgnoreCase(tmp.getName())==0){
	         			found =true;
	         			String move = st.nextToken();
	         			if(move.compareToIgnoreCase("FWD") == 0){
	         				int newCell = tmp.getNewCell();
	         				bmain.deleteContent(tmp.getLocation());
	         				tmp.setLocation(newCell);
	         				bmain.setAgent(tmp);
                                                feedBack=tmp.getName()+" was moved.";
	         			}
	         			else if((move.compareToIgnoreCase("RIGHT") == 0)||
	         					(move.compareTo("LEFT") == 0)){
	         						String newOrientation = tmp.getNewOrientation(move);
	         						bmain.deleteContent(tmp.getLocation());
	         						tmp.setOrientation(newOrientation);
	         						bmain.setAgent(tmp);
                                                                feedBack=tmp.getName()+" was moved.";
	         			}
	         			else{
	         				feedBack="Unknown move !!!";
	         			}
	         		}
	         	}
	         	if(i >= agentsVect.size() && !found)
	         		feedBack="Agent not Found !!!";
	         }
	         else{
	         	feedBack="Unknown command";
	         }
	     }	
            System.out.println(inn + " -> "+ feedBack);
	return feedBack;	
	}
	
	
	/**
	 * This is the main of the server application
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String args[]) throws IOException 
	{	
		DatagramSocket serverSocket = new DatagramSocket(9876); 
		while(true) 
		{ 
			byte[] receiveData = new byte[1024]; 
			byte[] sendData  = new byte[1024]; 
			DatagramPacket receivePacket = 
				new DatagramPacket(receiveData, receiveData.length); 
			serverSocket.receive(receivePacket); 
			String sentence = new String(receivePacket.getData());
			sentence=parseInput(sentence);
			
			InetAddress IPAddress = receivePacket.getAddress(); 
			
			int port = receivePacket.getPort(); 
			
			String capitalizedSentence = sentence.toUpperCase(); 
			
			sendData = capitalizedSentence.getBytes(); 
			
			DatagramPacket sendPacket = 
				new DatagramPacket(sendData, sendData.length, IPAddress, 
						port); 
			
			serverSocket.send(sendPacket); 
		}
	}
}

